package com.zhang.sharding.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

@Service
public class MyCustomShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyyMM");

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> preciseShardingValue) {
        Date date = preciseShardingValue.getValue();
        String monthStr = DATE_FORMATTER.format(date);
        int month = Integer.parseInt(monthStr.substring(4));
        int year = Integer.parseInt(monthStr.substring(0, 4));
        // 格式化Date对象为yyyyMM格式的字符串
        String suffix = DATE_FORMATTER.format(preciseShardingValue.getValue());
        // 计算出应该选择哪张表
        int tableIndex = (month - 1) / 3; // 每3个月一张表
        // 生成表名，例如 "global_event_log_202301"
        String targetTable = "global_event_log_" + String.format("%04d%02d", year,  (tableIndex * 3) + 1);

        if (availableTargetNames.contains(targetTable)) {
            return targetTable;
        } else {
            throw new IllegalArgumentException("Target table not found: " + targetTable);
        }

    }
}
